﻿using Abp.Domain.Repositories;
using Abp.Domain.Uow;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using System.Linq;
using System.Linq.Expressions;

namespace Magicodes.Admin.WULINGAddresss
{
    public class WULINGAddressManager: AdminDomainServiceBase, IWULINGAddressManager
    {
        private readonly IRepository<WULINGAddress, long> _wulingAddressRepository;

        public WULINGAddressManager(IRepository<WULINGAddress, long>  wulingAddressRepository)
        {
            _wulingAddressRepository = wulingAddressRepository;
        }

        [UnitOfWork]
        public async Task Import(IEnumerable<WULINGAddress> wulingAddresses) {

            var all =await _wulingAddressRepository.GetAllListAsync();
            var adds = new List<WULINGAddress>();
            var updates = new List<WULINGAddress>();
            foreach (var item in wulingAddresses)
            {
                //更新已经存在的
                var temp = all.SingleOrDefault(s=>s.ServiceStationCode==item.ServiceStationCode); 
                if (temp != null)
                {
                    updates.Add(item);

                }
                else
                {
                    adds.Add(item);
                }
            }
            foreach (var item in adds)
            {
              await  this._wulingAddressRepository.InsertAsync(item);
            }
            foreach (var item in updates)
            {
                await this._wulingAddressRepository.UpdateAsync(item);
            }
        }

        public async Task<WULINGAddress> GetByServiceStationCode( string code) {
            if (string.IsNullOrWhiteSpace(code))
                return null;
            var re =await _wulingAddressRepository.SingleAsync(s=>s.ServiceStationCode==code);

            return re;
        }

        public async Task<IReadOnlyList<WULINGAddress>> GetWULINGAddresss(string code,string name)
        { 
            var re = await _wulingAddressRepository.GetAllListAsync(s => s.ServiceStationCode.Contains( code) || s.ServiceStationName.Contains(name));

            return re;
        }
    }
}
